package com.xxx.grpc.server;

import com.xxx.grpc.protobuf.GreeterGrpc;
import com.xxx.grpc.protobuf.HelloReply;
import com.xxx.grpc.protobuf.HelloRequest;
import io.grpc.stub.StreamObserver;

/**
 * gRPC：接口实现类
 */
public class HelloServiceImpl extends GreeterGrpc.GreeterImplBase {

    @Override
    public void sayHello(HelloRequest request, io.grpc.stub.StreamObserver<HelloReply> responseObserver) {
        System.out.println("sayHello(). name: " + request.getName());
        HelloReply reply = HelloReply.newBuilder().setMessage("Hello, " + request.getName()).build();
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getAge(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
        String name = request.getName();
        System.out.println("getAge(). name: " + name);
        int age;
        if(name.equals("Alice")) {
            age = 18;
        } else if(name.equals("Bob")) {
            age = 20;
        } else {
            age = 0;
        }
        HelloReply reply = HelloReply.newBuilder().setMessage(name + " age: " + age).build();
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }
}
